Use AutoAI and timeseries data with supporting features to predict PM2.5 by ibm-watson-machine-learning¶

This notebook contains the steps and code to demonstrate support of AutoAI experiments for timeseries data sets in Watson Machine Learning service. It introduces commands for data retrieval, training experiments, persisting pipelines, testing pipelines, deploying pipelines, and scoring.

Some familiarity with Python is helpful. This notebook uses Python 3.9.

Learning goals¶

The learning goals of this notebook are:

  • Define Watson Machine Learning experiment for timeseries data sets with supporting features.
  • Work with experiments to train AutoAI models.
  • Compare trained models quality and select the best one for further deployment.
  • Online deployment and score the trained model.

Contents¶

This notebook contains the following parts:

  1. Setup
  2. Timeseries data sets
  3. Optimizer definition
  4. Experiment Run
  5. Pipelines comparison
  6. Deploy and Score
  7. Clean up
  8. Summary and next steps

1. Set up the environment¶

Before you use the sample code in this notebook, you must perform the following setup tasks:

  • Create a Watson Machine Learning (WML) Service instance (a free plan is offered and information about how to create the instance can be found here).
  • Create a Cloud Object Storage (COS) instance (a lite plan is offered and information about how to order storage can be found here).
    Note: When using Watson Studio, you already have a COS instance associated with the project you are running the notebook in.

Connection to WML¶

Authenticate the Watson Machine Learning service on IBM Cloud. You need to provide Cloud API key and location.

Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get a service specific url by going to the Endpoint URLs section of the Watson Machine Learning docs. You can check your instance location in your Watson Machine Learning (WML) Service instance details.

You can use IBM Cloud CLI to retrieve the instance location.

ibmcloud login --apikey API_KEY -a https://cloud.ibm.com
ibmcloud resource service-instance WML_INSTANCE_NAME

NOTE: You can also get a service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, and then copy the created key and paste it in the following cell.

Action: Enter your api_key and location in the following cell.

In [1]:
api_key = 'PUT_YOUR_KEY_HERE'
location = 'PASTE YOUR INSTANCE LOCATION HERE'
In [2]:
wml_credentials = {
    "apikey": api_key,
    "url": 'https://' + location + '.ml.cloud.ibm.com'
}

Install and import the ibm-watson-machine-learning and dependecies¶

Note: ibm-watson-machine-learning documentation can be found here.

In [3]:
!pip install -U ibm-watson-machine-learning | tail -n 1
!pip install wget | tail -n 1
!pip install plotly | tail -n 1
Successfully installed ibm-watson-machine-learning-1.0.229
Successfully installed wget-3.2
Requirement already satisfied: tenacity>=6.2.0 in /opt/conda/envs/Python-3.9/lib/python3.9/site-packages (from plotly) (8.0.1)
In [4]:
from ibm_watson_machine_learning import APIClient

client = APIClient(wml_credentials)

Working with spaces¶

You need to create a space that will be used for your work. If you do not have a space, you can use Deployment Spaces Dashboard to create one.

  • Click New Deployment Space
  • Create an empty space
  • Select Cloud Object Storage
  • Select Watson Machine Learning instance and press Create
  • Copy space_id and paste it below

Tip: You can also use SDK to prepare the space for your work. More information can be found here.

Action: assign space ID below

In [5]:
space_id = 'PASTE YOUR SPACE ID HERE'

You can use the list method to print all existing spaces.

In [ ]:
client.spaces.list(limit=10)

To be able to interact with all resources available in Watson Machine Learning, you need to set the space which you will be using.

In [7]:
client.set.default_space(space_id)
Out[7]:
'SUCCESS'

2. Timeseries data set¶

Connections to COS¶

In next cell we read the COS credentials from the space.

In [8]:
cos_credentials = client.spaces.get_details(space_id=space_id)['entity']['storage']['properties']

Training data sets¶

Download training data from git repository and upload it to a COS.
This example uses the China daily PM2.5.

In [9]:
datasource_name = 'bluemixcloudobjectstorage'
bucketname = cos_credentials['bucket_name']
In [10]:
import os, wget, zipfile

filename = 'PM25.csv'
base_url = 'https://raw.githubusercontent.com/wjcougar/air_pollution/master/'

if not os.path.isfile(filename): wget.download(base_url + filename)

Visualize the data¶

In [11]:
import plotly.express as px
import pandas as pd

df = pd.read_csv(filename)
fig = px.line(df, x='date', y=df.columns)
fig.show()

Create connection¶

In [12]:
conn_meta_props= {
    client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {datasource_name} ",
    client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(datasource_name),
    client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
    client.connections.ConfigurationMetaNames.PROPERTIES: {
        'bucket': bucketname,
        'access_key': cos_credentials['credentials']['editor']['access_key_id'],
        'secret_key': cos_credentials['credentials']['editor']['secret_access_key'],
        'iam_url': 'https://iam.cloud.ibm.com/identity/token',
        'url': cos_credentials['endpoint_url']
    }
}

conn_details = client.connections.create(meta_props=conn_meta_props)
Creating connections...
SUCCESS

Note: The above connection can be initialized alternatively with api_key and resource_instance_id.
The above cell can be replaced with:

conn_meta_props= {
    client.connections.ConfigurationMetaNames.NAME: f"Connection to Database - {db_name} ",
    client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_uid_by_name(db_name),
    client.connections.ConfigurationMetaNames.DESCRIPTION: "Connection to external Database",
    client.connections.ConfigurationMetaNames.PROPERTIES: {
        'bucket': bucket_name,
        'api_key': cos_credentials['apikey'],
        'resource_instance_id': cos_credentials['resource_instance_id'],
        'iam_url': 'https://iam.cloud.ibm.com/identity/token',
        'url': 'https://s3.us.cloud-object-storage.appdomain.cloud'
    }
}

conn_details = client.connections.create(meta_props=conn_meta_props)

In [13]:
connection_id = client.connections.get_uid(conn_details)

Training data connection¶

The code in next cell defines connections to created assets.

In [14]:
from ibm_watson_machine_learning.helpers import DataConnection, S3Location

data_connections = []
data_connection = DataConnection(
        connection_asset_id=connection_id,
        location=S3Location(bucket=cos_credentials['bucket_name'],
                            path=filename)
    )

data_connection.set_client(client)
data_connection.write(data=filename, remote_name=filename)
data_connections.append(data_connection)

3. Optimizer definition¶

Optimizer configuration¶

Provide the input information for AutoAI optimizer:

  • name - experiment name
  • prediction_type - type of the problem
  • prediction_columns - target columns names
  • timestamp_column_name — date&time column name/index
  • feature_columns – names/indices of supporting feature columns
  • forecast_window — future date/time range to be predicted
  • holdout_size - number of holdout records
  • lookback_window – past date/time range used for model training, -1 means auto-determined
  • backtest_num – number of backtests
  • supporting_features_at_forecast – whether leveraging future values of supporting features
  • pipeline_types – specify an indiviual or a group of pipelins by type
In [15]:
from ibm_watson_machine_learning.experiment import AutoAI
from ibm_watson_machine_learning.utils.autoai.enums import ForecastingPipelineTypes

experiment = AutoAI(wml_credentials, space_id=space_id)
forecast_window = 7
backtest_num = 4

pipeline_optimizer = experiment.optimizer(
            name="PM25 prediction",
            prediction_type=AutoAI.PredictionType.FORECASTING,
            prediction_columns=['pollution'],
            timestamp_column_name='date',
            feature_columns=['pollution','dew','temp','press','wnd_spd','snow','rain'],
            lookback_window=-1,
            backtest_num=backtest_num,
            holdout_size=14,
            forecast_window=forecast_window,
            supporting_features_at_forecast=True,
            pipeline_types=[ForecastingPipelineTypes.Bats] + ForecastingPipelineTypes.get_exogenous()
)

Configuration parameters can be retrieved via pipeline_optimizer.get_params().

4. Experiment run¶

Call the fit() method to trigger the AutoAI experiment. You can either use interactive mode (synchronous job) or background mode (asychronous job) by specifying background_model=True.

In [16]:
fit_details = pipeline_optimizer.fit(training_data_reference=data_connections, background_mode=False)
Training job 9ab9e7dd-a3c3-4498-92ae-148e6ad9b3a3 completed: 100%|████████| [04:35<00:00,  2.76s/it]

You can use the get_run_status() method to monitor AutoAI jobs in background mode.

In [17]:
pipeline_optimizer.get_run_status()
Out[17]:
'completed'

5. Pipelines comparison¶

You can list trained pipelines and evaluation metrics information in the form of a Pandas DataFrame by calling the summary() method. You can use the DataFrame to compare all discovered pipelines and select the one you like for further deployment.

In [18]:
summary = pipeline_optimizer.summary()
summary
Out[18]:
Enhancements Estimator Winner Type validation_symmetric_mean_absolute_percentage_error holdout_avg_r2 holdout_avg_mean_absolute_error holdout_avg_root_mean_squared_error holdout_avg_symmetric_mean_absolute_percentage_error holdout_mean_absolute_error ... holdout_symmetric_mean_absolute_percentage_error holdout_r2 backtest_avg_r2 backtest_avg_mean_absolute_error backtest_avg_root_mean_squared_error backtest_avg_symmetric_mean_absolute_percentage_error backtest_mean_absolute_error backtest_root_mean_squared_error backtest_symmetric_mean_absolute_percentage_error backtest_r2
Pipeline Name
Pipeline_4 HPO, FE Ensembler True exogenous 42.446582 0.570773 37.987089 61.398038 35.241435 37.987089 ... 35.241435 0.570773 0.649023 32.824713 48.311141 30.368102 32.824713 48.311141 30.368102 0.649023
Pipeline_1 HPO, FE RandomForest True exogenous 46.987713 0.267621 58.455268 80.200856 58.607427 58.455268 ... 58.607427 0.267621 0.283918 46.957749 56.460090 51.193633 46.957749 56.460090 51.193633 0.283918

2 rows × 21 columns

Check pipeline details by calling get_pipeline_details(). By default details of best pipeline are returned.

In [19]:
best_pipeline_name = summary[summary.Winner==True].index.values[0]
print('Best pipeline is:', best_pipeline_name)

pipeline_details = pipeline_optimizer.get_pipeline_details()
Best pipeline is: Pipeline_4

Holdout data visualization¶

In [29]:
from datetime import datetime, timedelta
import numpy as np

visualization = pipeline_details['visualization']['holdout']
holdout_dates = visualization['time']
holdout_predictions = visualization['predicted_values'][0]
holdout_observed_values = visualization['observed_values'][0]
holdout_df = pd.DataFrame({'time':holdout_dates, 'observed_values':holdout_observed_values, 'predicted_values': holdout_predictions})
fig = px.line(holdout_df, x="time", y=holdout_df.columns, hover_data={"time": "|%B %d, %Y"}, title='Holdout data')
fig.update_xaxes(dtick="M1", tickformat="%b\n%Y")
fig.show()

Backtest data visualization¶

In [21]:
from datetime import datetime, timedelta
import numpy as np

backtest_dfs = []
for i in range(backtest_num):
    visualization = pipeline_details['visualization']['backtest']['iterations'][i]
    backtest_dates = visualization['time']
    backtest_predictions = visualization['predicted_values'][0]
    observed_values = visualization['observed_values'][0]
    backtest_dfs.append(pd.DataFrame({'time':backtest_dates, 'observed_values':observed_values, 'predicted_values': backtest_predictions}))
backtest_df = pd.concat(backtest_dfs)
fig = px.line(backtest_df, x="time", y=backtest_df.columns, hover_data={"time": "|%B %d, %Y"}, title='Backtest data')
fig.update_xaxes(dtick="M1", tickformat="%b\n%Y")
fig.show()

6. Deploy and Score¶

In this section you will learn how to deploy and score pipeline model as online deployment using WML instance.

Online deployment creation¶

In [22]:
from ibm_watson_machine_learning.deployment import WebService

service = WebService(wml_credentials, source_space_id=space_id)

service.create(
    experiment_run_id=pipeline_optimizer.get_run_details()['metadata']['id'],
    model=best_pipeline_name, 
    deployment_name="PM2.5 Forecasting"
    )
Preparing an AutoAI Deployment...
Published model uid: 4dc9687c-01b7-472e-81c9-d62cd321e7fd
Deploying model 4dc9687c-01b7-472e-81c9-d62cd321e7fd using V4 client.


#######################################################################################

Synchronous deployment creation for uid: '4dc9687c-01b7-472e-81c9-d62cd321e7fd' started

#######################################################################################


initializing
Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead.
...
ready


------------------------------------------------------------------------------------------------
Successfully finished deployment creation, deployment_uid='97e8b6e2-6014-4506-b397-bd53361d2c48'
------------------------------------------------------------------------------------------------


To show all available information about the deployment use the .get_params() method:

In [23]:
service.get_params()
Note: online_url is deprecated and will be removed in a future release. Use serving_urls instead.
Out[23]:
{'entity': {'asset': {'id': '4dc9687c-01b7-472e-81c9-d62cd321e7fd'},
  'custom': {},
  'deployed_asset_type': 'model',
  'hybrid_pipeline_hardware_specs': [{'hardware_spec': {'name': 'S',
     'num_nodes': 1},
    'node_runtime_id': 'auto_ai.kb'}],
  'name': 'PM2.5 Forecasting',
  'online': {},
  'space_id': '4ac9b5cd-bde7-4f78-aa1a-103a784cdf9a',
  'status': {'online_url': {'url': 'https://us-south.ml.cloud.ibm.com/ml/v4/deployments/97e8b6e2-6014-4506-b397-bd53361d2c48/predictions'},
   'serving_urls': ['https://us-south.ml.cloud.ibm.com/ml/v4/deployments/97e8b6e2-6014-4506-b397-bd53361d2c48/predictions'],
   'state': 'ready'}},
 'metadata': {'created_at': '2022-07-23T14:14:51.191Z',
  'id': '97e8b6e2-6014-4506-b397-bd53361d2c48',
  'modified_at': '2022-07-23T14:14:51.191Z',
  'name': 'PM2.5 Forecasting',
  'owner': 'IBMid-270007DD7M',
  'space_id': '4ac9b5cd-bde7-4f78-aa1a-103a784cdf9a'},
 'system': {'warnings': [{'id': 'Deprecated',
    'message': 'online_url is deprecated and will be removed in a future release. Use serving_urls instead.'}]}}

Scoring¶

You can use the score method to get predictions for defined forecasting window. You can either send payload records or use empty list.

In [24]:
predictions = service.score(payload=pd.DataFrame({'daily_cases' : []}))
print('predictions for next 7 days:\n')
predictions
predictions for next 7 days:

Out[24]:
{'predictions': [{'fields': ['prediction'],
   'values': [[[129.5439294077758]],
    [[129.81703947189507]],
    [[126.70353558876782]],
    [[123.59116561586549]],
    [[126.16670897809692]],
    [[130.53538843411673]],
    [[134.82070412310827]]]}]}

Or you could send payload with new obeservations:

filename = 'PM25_NewObservations.csv'

if not os.path.isfile(filename): wget.download(base_url + filename)
predictions = service.score(pd.read_csv(filename).drop("date", axis=1))
predictions

Visualization of predictions¶

In [30]:
last_date = datetime.strptime(holdout_df.tail(1).time.values.tolist()[0],'%Y-%m-%d')
prediction_dates = [(last_date + timedelta(days=1 + i)).date() for i in range(forecast_window)]
prediction_values = [pred[0][0] for pred in  predictions['predictions'][0]['values']]
pred_df = pd.DataFrame({'time' : holdout_dates + prediction_dates,
                        'observed_values' : holdout_observed_values + [np.NAN for i in range(forecast_window)],
                        'predicted_values' : holdout_predictions + prediction_values})

fig = px.line(pred_df, x="time", y=pred_df.columns, hover_data={"time": "|%B %d, %Y"}, title='Forecast data')
fig.update_xaxes(dtick="M1", tickformat="%b\n%Y")
fig.show()

7. Clean up¶

If you want to clean up all created assets:

  • experiments
  • trainings
  • pipelines
  • model definitions
  • models
  • functions
  • deployments

please follow up this sample notebook.

8. Summary and next steps¶

You successfully completed this notebook!.

You learned how to use ibm-watson-machine-learning to run AutoAI experiments.

Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Authors¶

Jun Wang, is a Software Architect and Data Scientist at IBM with a track record of developing enterprise-level applications that substantially increases clients' ability to turn data into actionable knowledge.

Copyright © 2020, 2021, 2022 IBM. This notebook and its source code are released under the terms of the MIT License.